package com.fz.study.project.utils;

import lombok.Data;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/*
* 基于redis的id生成器
* */
@Component
@Data
public class RedisIdWorker {

    private final StringRedisTemplate stringRedisTemplate;
    private static int COUNT_BITS = 32;

//    配置最开始的时间为2024-01-01 00:00:00
    private static final long BEGIN_TIMESTAMP = 1704067200L;
    public long nextId(String keyPrefix){
//        生成时间戳
//        获取当前时间
        LocalDateTime now = LocalDateTime.now();
//        获取当前时间的秒数
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
//        得到当前时间戳
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

//        生成序列号
//        获取当前时间，精确到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
//        使用redis的自增长
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
//        拼接并返回
        return timestamp << COUNT_BITS | count;
    }

    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.of(2024, 1, 1, 0, 0, 0);
//        获取该时间的秒数
        long time = localDateTime.toEpochSecond(ZoneOffset.UTC);
        System.out.println(time);

    }
}
